package com.yonyou.jrmob.contacts.contact.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Toast;


import com.github.ybq.android.spinkit.SpinKitView;
import com.yonyou.jrmob.contacts.R;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;

import jrmob.yonyou.com.commonlib.app_config_tool.tool.base.MobUtils;
import jrmob.yonyou.com.commonlib.app_config_tool.tool.base.StatusBarUtil;
import jrmob.yonyou.com.commonlib.baseui.base.BaseActivityMob_lib;
import uk.co.senab.photoview.PhotoView;
import uk.co.senab.photoview.PhotoViewAttacher;

public class HeadImageActivity_ct extends BaseActivityMob_lib {
    private static final String TAG = HeadImageActivity_ct.class.getSimpleName();
    private View rootView;
    private String url;
    private PhotoView mPhotoView;
    private ImageView gifImageView;
    private PopupWindow mPopupWindow;
    /**
     * 图片存储路径
     *//*
    public static String IMAGE_PATH
            = Environment.getExternalStorageDirectory().getAbsolutePath() + "/JRMOB";*/
    //private final String ALBUM_PATH = Constant.IMAGE_PATH;
    private final String ALBUM_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/LryAPP";
    private MyLongClickListener mMyLongClickListener;
    private SpinKitView loading;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        rootView = LayoutInflater.from(this).inflate(R.layout.activity_head_image_ct, null);
        setContentView(rootView);
        StatusBarUtil.transparencyBar(this);
        initView();
        getDataFromIntent();
        initListener();
        showImage();
    }

    @Override
    public void initListener() {
        mMyLongClickListener = new MyLongClickListener();
        mPhotoView.setOnViewTapListener(new PhotoViewAttacher.OnViewTapListener() {
            @Override
            public void onViewTap(View view, float x, float y) {
                finish();
            }
        });
        mPhotoView.setClickable(true);
        //设置长按监听
        mPhotoView.setOnLongClickListener(mMyLongClickListener);

        gifImageView.setClickable(true);
        gifImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        gifImageView.setClickable(true);
        //设置长按监听
        gifImageView.setOnLongClickListener(mMyLongClickListener);
    }

    @Override
    public void initData() {

    }

    private void getDataFromIntent() {
        try {
            Intent intent = getIntent();
            url = intent.getStringExtra("url");
            Log.d(TAG, "getDataFromIntent: uri = " + url);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showImage() {
        Log.d(TAG, "showImage: " + url.substring(url.lastIndexOf(".") + 1));
        if ("gif".equals(url.substring(url.lastIndexOf(".") + 1))) {
            mPhotoView.setVisibility(View.GONE);
            gifImageView.setVisibility(View.VISIBLE);
           /* Glide.with(this)
                    .load(url)
                    .diskCacheStrategy(DiskCacheStrategy.SOURCE)//缓存多个尺寸
                    .error(R.mipmap.im_skin_icon_imageload_failed_ct)
                    .into(new GlideDrawableImageViewTarget(gifImageView) {
                        @Override
                        public void onLoadStarted(Drawable placeholder) {
                            super.onLoadStarted(placeholder);
                            loading.setVisibility(View.VISIBLE);
                        }

                        @Override
                        public void onLoadFailed(Exception e, Drawable errorDrawable) {
                            super.onLoadFailed(e, errorDrawable);
                            loading.setVisibility(View.GONE);
                        }

                        @Override
                        public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> animation) {
                            super.onResourceReady(resource, animation);
                            loading.setVisibility(View.GONE);
                        }
                    });*/
        } else {
           /* Glide.with(this)
                    .load(url)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)//缓存多个尺寸
                    .thumbnail(0.1f)//先显示缩略图  缩略图为原图的1/10
                    .error(R.mipmap.im_skin_icon_imageload_failed_ct)
                    .into(new GlideDrawableImageViewTarget(mPhotoView) {
                        @Override
                        public void onLoadStarted(Drawable placeholder) {
                            super.onLoadStarted(placeholder);
                            loading.setVisibility(View.VISIBLE);
                        }

                        @Override
                        public void onLoadFailed(Exception e, Drawable errorDrawable) {
                            super.onLoadFailed(e, errorDrawable);
                            loading.setVisibility(View.GONE);
                        }

                        @Override
                        public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> animation) {
                            super.onResourceReady(resource, animation);
                            loading.setVisibility(View.GONE);
                        }
                    });*/
        }
    }
    @Override
    public void initView() {
        mPhotoView = (PhotoView) findViewById(R.id.pvHeadImage);
        gifImageView = (ImageView) findViewById(R.id.ivHeadImage);
        loading = (SpinKitView) findViewById(R.id.loadingHeadImage);
    }

    private void callService2downloadImage(final String url) {
       /* Glide.with(getApplicationContext()).load(url).asBitmap().into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                Log.d(TAG, "onResourceReady: resource = " + resource.getByteCount());
                String fileName = "";
                if ("gif".equals(url.substring(url.lastIndexOf(".") + 1))) {
                    fileName = String.valueOf("/" + System.currentTimeMillis() + ".gif");
                } else {
                    fileName = String.valueOf("/" + System.currentTimeMillis() + ".jpg");
                }
                Log.d(TAG, "onResourceReady: url = " + url);
                boolean isSaved = saveFile(resource, fileName);
                if (isSaved) {
                    Toast.makeText(HeadImageActivity_ct.this, "保存图片在 " + ALBUM_PATH + " 下成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(HeadImageActivity_ct.this, "保存失败", Toast.LENGTH_SHORT).show();
                }
            }
        });*/

    }

    /**
     * 保存文件
     *
     * @param bm
     * @param fileName
     */
    public boolean saveFile(Bitmap bm, String fileName) {
        //TODO 保存gif图片
        boolean isSaved = false;
        try {
            File dirFile = new File(ALBUM_PATH);
            if (!dirFile.exists()) {
                dirFile.mkdir();
            }
            File path = new File(ALBUM_PATH);
            if (!path.exists())
                path.mkdirs();

            File myCaptureFile = new File(ALBUM_PATH + fileName);
            if (!myCaptureFile.exists()) {
                myCaptureFile.createNewFile();
            }
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
            isSaved = bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
            Log.d(TAG, "saveFile: myCaptureFile = " + myCaptureFile.exists() + " myCaptureFile path = " + myCaptureFile.getAbsolutePath());
            if (isSaved) {// 通知系统更新图库文件
                Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                Uri uri = Uri.fromFile(myCaptureFile);
                intent.setData(uri);
                sendBroadcast(intent);
            }
            bos.flush();
            bos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isSaved;
    }

    private void showPopupWindow() {
        // 设置屏幕透明度
        MobUtils.setBackgroundAlpha(HeadImageActivity_ct.this, 0.3f);

        View view = LayoutInflater.from(HeadImageActivity_ct.this).inflate(
                R.layout.item_image_download_popup_ct, null);
        view.findViewById(R.id.item_download_image_popup_save).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(url)) {
                    mPopupWindow.dismiss();
                    Log.d(TAG, "onClick: 222222");
                    callService2downloadImage(url);
                }
            }
        });
        view.findViewById(R.id.item_download_image_popup_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPopupWindow.dismiss();
            }
        });
        // 创建popWindow
        mPopupWindow = new PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        mPopupWindow.setAnimationStyle(R.style.bottom_pop_anim);
        // 要让其中的view获取焦点，必须设置为true
        mPopupWindow.setFocusable(true);
        mPopupWindow.setOutsideTouchable(true);
        ColorDrawable dw = new ColorDrawable(0000000000);
        // 还必须设置一个背景图片
        mPopupWindow.setBackgroundDrawable(dw);
        mPopupWindow.setTouchable(true);
        mPopupWindow.setTouchInterceptor(new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
                    mPopupWindow.dismiss();
                    return true;
                }
                return false;
            }
        });
        // 设置点击外部消失
        mPopupWindow.setOutsideTouchable(true);
        // 可以显示在底部
        mPopupWindow.showAtLocation(rootView,
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
//         设置layout在PopupWindow中显示的位置
        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                // 设置屏幕透明度
                MobUtils.setBackgroundAlpha(HeadImageActivity_ct.this, 1f);
            }
        });


    }

    /**
     * photoView长按事件监听
     */
    private class MyLongClickListener implements View.OnLongClickListener {

        @Override
        public boolean onLongClick(View v) {
            showPopupWindow();
            return true;
        }
    }

    public void backMethod() {

    }
}
